package com.tim.app.server.api;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;

import com.application.library.net.ResponseCallback;
import com.lzy.okhttputils.cache.CacheMode;
import com.lzy.okhttputils.model.HttpParams;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.net.HttpMethod;
import com.tim.app.server.net.NetworkInterface;
import com.tim.app.server.util.BitmapDecoder;
import com.tim.app.server.util.BitmapSize;
import com.tim.app.util.FileSizeUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

/**
 * 初始化
 */
public class API_App {

    private static volatile API_App api = null;

    private static String API_APP_SCHEME = "";

    public static final String INTT_SERVER = "/moli_discover_consumer/v1/clienturl/selectDataClienturl";//初始化推送

    public static final String SELECT_LIST = "/moli_discover_consumer/discover/v1.1/selectDiscoverInfoV1Dot1";//主页精选列表

    private static final String SEARCH = "/moli_discover_consumer/v1/search/appSearch";//搜索

    private static final String UPLOAD_FILE = "/moli_discover_consumer/v1/fileCommonUpload/uploadFile";//文件上传

    private API_App() {

    }

    public static API_App ins() {
        if (api == null) {
            synchronized (API_App.class) {
                if (api == null) {
                    api = new API_App();
                    switch (RT.HOST) {
                        case DEVELOP:
//                             API_APP_SCHEME = "http://192.168.1.20:8082";
//                            API_APP_SCHEME = "http://192.168.1.26:8082";
                            API_APP_SCHEME = "http://192.168.1.28:8086";
                            break;
                        case DEBUG:
                            API_APP_SCHEME = "";
                            break;
                        case PUBLISH:
                            API_APP_SCHEME = "";
                            break;
                    }
                }
            }
        }
        return api;
    }

    /**
     * 获取服务器地址
     *
     * @param tag
     * @param version     客户端版本号
     * @param packageName 项目包名
     * @param appChannel  客户端渠道名
     * @param callback
     */
    public void getServerAddress(String tag, String version, String packageName, String appChannel, ResponseCallback callback) {
        String url = API_APP_SCHEME + INTT_SERVER;
        HashMap params = new HashMap();
        params.put("clientVersion", version);
        params.put("clientType", packageName);
        params.put("clientName", appChannel);
        NetworkInterface.ins().connected(HttpMethod.GET, url, tag, params, CacheMode.DEFAULT, false, callback);
    }

    /**
     * 获取精选页面数据
     *
     * @param tag
     * @param pageNum
     * @param callback
     */
    public void getSelectedData(String tag, int pageNum, CacheMode mode, ResponseCallback callback) {
        String url = API_APP_SCHEME + SELECT_LIST;
        HashMap<String, Object> params = new HashMap<>();
        if (UserManager.ins().isLogin()) {
            params.put("uid", UserManager.ins().getUserId());
        }
        params.put("pageNum", pageNum);
        NetworkInterface.ins().connected(HttpMethod.GET, url, tag, params, mode, false, callback);
    }


    /**
     * 搜索
     * http://doc.java.duailin.top/api/project.do#/ffff-1494851847113-1722617555-0002/front/interfaceDetail/ffff-1496910918027-1722617555-0011
     *
     * @param tag
     * @param searchType
     * @param keyWord
     * @param pageNum
     * @param pageSize
     * @param callback
     */
    public void search(String tag, String searchType, String keyWord, int pageNum, int pageSize, ResponseCallback callback) {
        String url = API_APP_SCHEME + SEARCH;
        HashMap<String, Object> params = new HashMap<>();
        params.put("title", keyWord);
        if (UserManager.ins().isLogin()) {
            params.put("uid", UserManager.ins().getUserId());
        }
        params.put("type", searchType);
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        params.put("systemType", 1);
        NetworkInterface.ins().connected(HttpMethod.GET, url, tag, params, CacheMode.DEFAULT, false, callback);
    }

    /**
     * 上传图片
     *
     * @param tag
     * @param filePath
     * @param callback
     */
    public void uploadAvatarData(String tag, String filePath, ResponseCallback callback) {
        String url = API_APP_SCHEME + UPLOAD_FILE;
        Bitmap bm = BitmapFactory.decodeFile(filePath);
        int w;
        int h;
        if (bm.getWidth() > 750) {
            w = 750;
            h = 750;
        } else {
            w = bm.getWidth();
            h = bm.getHeight();
        }


        BitmapSize size = new BitmapSize(w, h);
        Bitmap bitmap = BitmapDecoder.decodeSampledBitmapFromFile(filePath, size, null);

        if (bitmap == null) {
            callback.onResponse(null, -1, RT.getString(R.string.upload_picture_failed), 0, false);
            return;
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();// 初始化一个流对象
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, output);// 把bitmap100%高质量压缩 到
        // output对象里


        byte[] result = output.toByteArray();// 转换成功了
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        File tempFile = new File(RT.defaultImage + "temp.jpg");
        if (tempFile.exists()) {
            tempFile.delete();
        }

        bitmap.recycle();// 自由选择是否进行回收
        bm.recycle();
        bitmap = null;
        bm = null;

        FileOutputStream fos;
        try {
            tempFile.createNewFile();
            fos = new FileOutputStream(tempFile);
            fos.write(result);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (tempFile == null || !tempFile.exists() || tempFile.length() <= 0) {
            callback.onResponse(null, -1, RT.getString(R.string.upload_picture_failed), 0, false);
            return;
        }

        HttpParams params = new HttpParams();
        params.put("Filedata", tempFile);
        NetworkInterface.ins().upload(url, tag, params, callback);
    }

    /**
     * 上传图片
     *
     * @param tag
     * @param filePath
     * @param callback
     */
    public void uploadData(String tag, String filePath, ResponseCallback callback) {
        String url = API_APP_SCHEME + UPLOAD_FILE;
        int w = 640;
        int h = 1136;

        BitmapSize size = new BitmapSize(w, h);

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inPurgeable = true;
        options.inInputShareable = true;
        BitmapFactory.decodeFile(filePath, options);
        int width = options.outWidth;
        int height = options.outHeight;
        Bitmap bitmap = null;

        if (((double) width / height) < 0.35 || ((double) height / width) < 0.35 || FileSizeUtil.getFileOrFilesSize(filePath, FileSizeUtil.SIZETYPE_KB) < 300) {
            bitmap = BitmapDecoder.decodeFile(filePath);
        } else {
            bitmap = BitmapDecoder.decodeSampledBitmapFromFile(filePath, size, null);
        }

        if (bitmap == null) {
            callback.onResponse(null, -1, RT.getString(R.string.upload_picture_failed), 0, false);
            return;
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();// 初始化一个流对象
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);// 把bitmap100%高质量压缩 到
        // output对象里

        bitmap.recycle();// 自由选择是否进行回收

        byte[] result = output.toByteArray();// 转换成功了
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        File tempFile = new File(RT.defaultImage + "temp.png");
        if (tempFile.exists()) {
            tempFile.delete();
        }

        FileOutputStream fos;
        try {
            tempFile.createNewFile();
            fos = new FileOutputStream(tempFile);
            fos.write(result);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (tempFile == null || !tempFile.exists() || tempFile.length() <= 0) {
            callback.onResponse(null, -1, RT.getString(R.string.upload_picture_failed), 0, false);
            return;
        }

        HttpParams params = new HttpParams();
        params.put("Filedata", tempFile);
        NetworkInterface.ins().upload(url, tag, params, callback);
    }

    /**
     * 上传录音
     *
     * @param tag
     * @param filePath
     * @param callback
     */
    public void uploadRecordData(String tag, String filePath, ResponseCallback callback) {
        String url = API_APP_SCHEME + UPLOAD_FILE;
        File tempFile = new File(filePath);

        if (tempFile == null || !tempFile.exists() || tempFile.length() <= 0) {
            callback.onResponse(null, -1, RT.getString(R.string.upload_picture_failed), 0, false);
            return;
        }

        HttpParams params = new HttpParams();
        params.put("Filedata", tempFile);
        NetworkInterface.ins().upload(url, tag, params, callback);
    }


    public int getBitmapSize(Bitmap bitmap) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {    //API 19
            return bitmap.getAllocationByteCount();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {//API 12
            return bitmap.getByteCount();
        }
        return bitmap.getRowBytes() * bitmap.getHeight();                //earlier version
    }


    /**
     * 上传图片
     *
     * @param tag
     * @param bitmapData
     * @param callback
     */
    public void uploadData(String tag, Bitmap bitmapData, ResponseCallback callback) {
        String url = API_APP_SCHEME + UPLOAD_FILE;

        if (bitmapData == null) {
            callback.onResponse(null, -1, RT.getString(R.string.upload_picture_failed), 0, false);
            return;
        }
        int w = bitmapData.getWidth();
        int h = bitmapData.getHeight();

        Bitmap bitmap = Bitmap.createScaledBitmap(bitmapData, w, h, true);

        ByteArrayOutputStream output = new ByteArrayOutputStream();// 初始化一个流对象
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, output);// 把bitmap100%高质量压缩 到
        // output对象里


        byte[] result = output.toByteArray();// 转换成功了
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        File tempFile = new File(RT.defaultImage + "temp.jpg");
        if (tempFile.exists()) {
            tempFile.delete();
        }

        FileOutputStream fos;
        try {
            tempFile.createNewFile();
            fos = new FileOutputStream(tempFile);
            fos.write(result);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        bitmap.recycle();// 自由选择是否进行回收

        if (tempFile == null || !tempFile.exists() || tempFile.length() <= 0) {
            callback.onResponse(null, -1, RT.getString(R.string.upload_picture_failed), 0, false);
            return;
        }

        HttpParams params = new HttpParams();
        params.put("Filedata", tempFile);
        NetworkInterface.ins().upload(url, tag, params, callback);
    }

}
